package com.mazihao.emos.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.mazihao.emos.db.dao.TbDeptDao;
import com.mazihao.emos.db.dao.TbUserDao;
import com.mazihao.emos.db.pojo.MessageEntity;
import com.mazihao.emos.db.pojo.TbMessage;
import com.mazihao.emos.db.pojo.TbUser;
import com.mazihao.emos.exception.EmosException;
import com.mazihao.emos.service.UserService;
import com.mazihao.emos.task.MessageTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author mazihao
 */
@Service
@Slf4j
@Scope("prototype")
public class UserServiceImpl implements UserService {
    // 小程序appId
    @Value("${wx.app-id}")
    private String appId;

    // 小程序appSecret
    @Value("${wx.app-secret}")
    private String appSecret;

    @Resource
    private TbUserDao userDao;

    @Resource
    private MessageTask messageTask;

    @Resource
    private TbDeptDao deptDao;

    private String getOpenId(String code) { // 获取openId
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        HashMap<String, Object> map = new HashMap<>();
        map.put("appid", appId);
        map.put("secret", appSecret);
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        String response = HttpUtil.post(url, map);
        JSONObject json = JSONUtil.parseObj(response);
        String openId = json.getStr("openid");
        if (openId == null || openId.isEmpty()) {
            throw new RuntimeException("临时登录凭证错误");
        }
        return openId;
    }

    @Override
    public int registerUser(String registerCode, String code, String nickname, String photo) {
        // 如果邀请码是000000,代表是超级管理员
        if ("000000".equals(registerCode)) {
            // 查询超级管理员账户是否已经绑定
            boolean bool = userDao.haveRootUser();
            if (!bool) {
                // 把当前用户绑定到ROOT账户
                String openId = getOpenId(code);
                HashMap<String, Object> param = new HashMap<>();
                param.put("openId", openId);
                param.put("nickname", nickname);
                param.put("photo", photo);
                param.put("role", "[0]");
                param.put("status", 1);
                param.put("createTime", new Date());
                param.put("root", true);
                userDao.insert(param);
                int id = userDao.searchIdByOpenId(openId);
                TbMessage entity = new TbMessage();
                entity.setSenderId(0);
                entity.setSenderName("系统消息");
                entity.setMsg("超级管理员已被注册");
                entity.setSendTime(new Date());
                messageTask.sendAsync(id + "", entity);
                return id;
            } else {
                // ROOT已经被绑定,就抛出异常
                throw new EmosException("超级管理员账号已被注册");
            }
        }
        return 0;
    }

    @Override
    public Set<String> searchUserPermissions(int userId) {
        return userDao.searchUserPermissions(userId);
    }

    @Override
    public Integer login(String code) {
        String openId = getOpenId(code);
        Integer id = userDao.searchIdByOpenId(openId);
        if (id == null) {
            throw new EmosException("账户不存在");
        }
        // 从消息队列中接收消息,转移到消息表
//        messageTask.receiveAsync(id + "");
        return id;
    }

    @Override
    public TbUser searchById(int userId) {
        return userDao.searchById(userId);
    }

    @Override
    public String searchUserHireDate(int userId) {
        return userDao.searchUserHireDate(userId);
    }

    @Override
    public HashMap<String, Object> searchUserSummary(int userId) {
        return userDao.searchUserSummary(userId);
    }

    @Override
    public ArrayList<HashMap<String, Object>> searchUserGroupByDept(String keyword) {
        ArrayList<HashMap<String, Object>> list1 = deptDao.searchDeptMembers(keyword);
        ArrayList<HashMap<String, Object>> list2 = userDao.searchUserGroupByDept(keyword);
        for (HashMap<String, Object> map1 : list1) {
            long deptId = (long) map1.get("id");
            ArrayList<HashMap<String, Object>> members = new ArrayList<>();
            for (HashMap<String, Object> map2 : list2) {
                long id = (long) map2.get("deptId");
                if (deptId == id) {
                    members.add(map2);
                }
            }
            map1.put("members", members);
        }
        return list1;
    }

    @Override
    public ArrayList<HashMap<String, Object>> searchMembers(List<Integer> params) {
        return userDao.searchMembers(params);
    }


}
